/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.netcracker.test.eleven;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author I
 */
public class MyLockFair {
    static boolean flag_lock;
    Queue<Thread> list_thread = new LinkedList<Thread>();
    
    public void Lock(){
        if(!flag_lock){
            flag_lock=true;
        }
        else{
            try {
                synchronized(this){
                    list_thread.add(Thread.currentThread());
                    Thread.currentThread().wait();
                }
                } catch (InterruptedException ex) {
                Logger.getLogger(MyLock.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
           
    }
    
    public void unLock(){
        if(flag_lock){
            flag_lock=false;
            synchronized(this){
                if(!list_thread.isEmpty()){
                    list_thread.poll().notify();
                }
            }
        }
    }
    
    public boolean tryLock(){ 
        if(!flag_lock){
            flag_lock=true;
            return true;
        }
        else{
            return false;
        } 
    }
    public boolean tryLock(long millisec){
        long count=0;
        boolean flag = false;
        while(true){
            try {
                if(count>=millisec)
                    break;
                TimeUnit.MILLISECONDS.sleep(1);
                
                if(!flag_lock){
                    flag_lock=true;
                    return true;
                }
                
            } catch (InterruptedException ex) {
                Logger.getLogger(MyLock.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return flag;
    }
}
